//
//  LGCheckPasswordController.m
//  BreathTrainingTool
//
//  Created by 1234 on 2024/5/21.
//  修改密码-验证原密码

#import "LGCheckPasswordController.h"
//修改密码
#import "LGRevisePasswordController.h"
@interface LGCheckPasswordController ()
/**   */
@property (nonatomic , strong)UIView *passwordView;
/**   */
@property (nonatomic , strong)UITextField *passwordTF;
/**   */
@property (nonatomic , strong)UIView *smscodeView;
/**   */
@property (nonatomic , strong)UITextField *smscodeTF;
/**   */
@property (nonatomic , strong)UIButton *codeBtn;
/**   */
@property (nonatomic , strong)UIButton *nextBtn;
/**   */
@property (nonatomic , copy)NSString *type;
/**   */
@property (nonatomic , copy)NSString *smsid;
/**   */
@property (nonatomic , strong)NSTimer *timer;
/**   */
@property (nonatomic , assign)NSInteger seconds;

@end

@implementation LGCheckPasswordController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.type = @"password";
    self.title = @"修改密码";
    [self createSubView];
}

//使用验证码登录
-(void)checkTypeBtnAction:(UIButton *)sender{
    if (sender.superview == self.passwordView) {
        self.type = @"code";
        self.passwordView.hidden = YES;
        self.smscodeView.hidden = NO;
        [self getSmsCodeAction:self.codeBtn];
    }else{
        self.type = @"password";
        self.passwordView.hidden = NO;
        self.smscodeView.hidden = YES;
    }
}

//获取验证码
-(void)getSmsCodeAction:(UIButton *)sender{
    NSString *phoneNum = [self.currentPhone stringByReplacingOccurrencesOfString:@" " withString:@""];
    if([self checkTelNumber:phoneNum] == NO){
        [TooltipView showMessage:@"请输入正确的手机号" offset:0];
        return;
    }
    [RequestUtil withPOST:@"/brbot-resource/sms/endpoint/send-validate" parameters:@{@"phone":phoneNum} header:NO success:^(NSInteger code, NSString *message, id returnData) {
        if(code == 200){
            self.seconds = 60;
            [self.timer invalidate];
            self.timer = nil;
            self.codeBtn.selected = YES;
            self.codeBtn.userInteractionEnabled = NO;
            self.smsid = LGNSString(returnData[@"id"]);
            self.codeBtn.frame = CGRectMake(Screen_W-viewPix(32)-viewPix(120), 0, viewPix(120), viewPix(56));
            [self.codeBtn setTitle:[NSString stringWithFormat:@"重新发送(%ld)",self.seconds] forState:UIControlStateNormal];
            self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countDownAction) userInfo:nil repeats:YES];
            [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
        }else{
            [TooltipView showMessage:message offset:0];
        }
    } error:^(NSError *error) {
        
    }];
}

//验证码倒计时
-(void)countDownAction{
    self.seconds--;
    [self.codeBtn setTitle:[NSString stringWithFormat:@"重新发送(%ld)",self.seconds] forState:UIControlStateNormal];
    if (self.seconds == 0) {
        self.codeBtn.frame = CGRectMake(Screen_W-viewPix(32)-viewPix(100), 0, viewPix(100), viewPix(56));
        self.codeBtn.selected = NO;
        self.codeBtn.userInteractionEnabled = YES;
        [self.codeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        [self.timer invalidate];
        self.timer = nil;
    }
}

//判断手机格式
- (BOOL)checkTelNumber:(NSString *)telNumber{
    NSString *pattern = @"^1+[0123456789]+\\d{9}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",pattern];
    BOOL isMatch = [pred evaluateWithObject:telNumber];
    return isMatch;
}

//下一步
-(void)nextBtnAction{
    NSString *phone = [self.currentPhone stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSMutableDictionary *tempDic = [NSMutableDictionary dictionaryWithDictionary:@{@"tenantId":@"000699"}];
    NSString *action = @"";
    if([self.type isEqualToString:@"code"]){
        //手机号验证
        action = @"brbot-auth/oauth/sms/token";
        [tempDic setValue:phone forKey:@"phone"];
        [tempDic setValue:self.smscodeTF.text forKey:@"smsCode"];
        [tempDic setValue:self.smsid forKey:@"smsId"];
        [tempDic setValue:@"mobile" forKey:@"grant_type"];
    }else{
        //密码验证
        NSString *password = self.passwordTF.text;
        action = @"/brbot-auth/oauth/tokenR";
        [tempDic setValue:phone forKey:@"username"];
        [tempDic setValue:password.md5String forKey:@"password"];
        [tempDic setValue:@"password" forKey:@"grant_type"];
    }
    [RequestUtil withPOST:action parameters:tempDic header:YES success:^(NSInteger code, NSString *message, id returnData) {
        if(code == 200){
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            [userDefaults setValue:LGNSString(returnData[@"user_id"]) forKey:@"userid"];
            [userDefaults setValue:LGNSString(returnData[@"dept_id"]) forKey:@"departid"];
            [userDefaults setValue:LGNSString(returnData[@"access_token"]) forKey:@"access_token"];
            [userDefaults setValue:LGNSString(returnData[@"username"]) forKey:@"phone"];
            [userDefaults setValue:LGNSString(returnData[@"realname"]) forKey:@"realname"];
            [userDefaults setValue:@"Y" forKey:@"islogin"];
            [userDefaults synchronize];
            //验证通过--去修改密码
            LGRevisePasswordController *controller = [[LGRevisePasswordController alloc]init];
            [self.navigationController pushViewController:controller animated:YES];
        }else{
            [TooltipView showMessage:message offset:0];
        }
    } error:^(NSError *error) {
        [TooltipView showMessage:LGErrorMessage offset:0];
    }];
}

#pragma mark
#pragma mark ====> 创建控件
-(void)createSubView{
    [self createPasswordView];
    [self createSmscodeView];
    [self.view addSubview:self.nextBtn];
}

-(void)createPasswordView{
    self.passwordView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, Screen_H)];
    self.passwordView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.passwordView];
    
    UILabel *titleLabel = [UILabel lableWithText:@"请输入原密码" colorString:@"#282828" textFont:LGFontWeight(16, UIFontWeightMedium) textAlignment:NSTextAlignmentLeft lines:1];
    titleLabel.frame = CGRectMake(viewPix(16), viewPix(24), Screen_W-viewPix(32), viewPix(24));
    [self.passwordView addSubview:titleLabel];
    
    [self.passwordView addSubview:self.passwordTF];
    
    UIButton *phoneBtn = [UIButton buttonWithTitle:@"使用手机号进行验证" titleFont:LGFont(14) textColor:@"#999999" frame:CGRectMake(Screen_W-viewPix(176), viewPix(123), viewPix(160), viewPix(30))];
    [phoneBtn setImage:[UIImage imageNamed:@"grayTip16"] forState:UIControlStateNormal];
    [phoneBtn setButtonInsetsStyle:LGButtonInsetsStyleRight marginSpace:2];
    [phoneBtn addTarget:self action:@selector(checkTypeBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.passwordView addSubview:phoneBtn];
}

-(void)createSmscodeView{
    self.smscodeView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, Screen_H)];
    self.smscodeView.backgroundColor = [UIColor whiteColor];
    self.smscodeView.hidden = YES;
    [self.view addSubview:self.smscodeView];
    
    NSString *phoneStr = @"";
    if (self.currentPhone.length>0) {
        phoneStr = [self.currentPhone stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
    }
    
    UILabel *titleLabel = [UILabel lableWithText:[NSString stringWithFormat:@"我们已向您手机号为 %@ 的手机发送验证码短信，请注意查收",phoneStr] colorString:@"#282828" textFont:LGFont(16) textAlignment:NSTextAlignmentLeft lines:2];
    titleLabel.frame = CGRectMake(viewPix(16), viewPix(24), Screen_W-viewPix(32), 48);
    [self.smscodeView addSubview:titleLabel];
    [self.smscodeView addSubview:self.smscodeTF];
    [self.smscodeTF addSubview:self.codeBtn];
    
    UIButton *phoneBtn = [UIButton buttonWithTitle:@"使用密码进行验证" titleFont:LGFont(14) textColor:@"#999999" frame:CGRectMake(Screen_W-viewPix(176), viewPix(147), viewPix(160), viewPix(30))];
    [phoneBtn setImage:[UIImage imageNamed:@"grayTip16"] forState:UIControlStateNormal];
    [phoneBtn setButtonInsetsStyle:LGButtonInsetsStyleRight marginSpace:2];
    [phoneBtn addTarget:self action:@selector(checkTypeBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.smscodeView addSubview:phoneBtn];
}

-(UITextField *)passwordTF{
    if(!_passwordTF){
        _passwordTF = [[UITextField alloc]initWithFrame:CGRectMake(viewPix(16), viewPix(60), Screen_W-viewPix(32), viewPix(56))];
        _passwordTF.backgroundColor = [UIColor colorWithString:@"#F2F1F8"];
        _passwordTF.tintColor = [UIColor colorWithString:@"#282828"];
        _passwordTF.textColor = [UIColor colorWithString:@"#282828"];
        _passwordTF.textAlignment = NSTextAlignmentLeft;
        _passwordTF.keyboardType = UIKeyboardTypePhonePad;
        _passwordTF.placeholder = @"请输入";
        _passwordTF.cornerRidus = viewPix(28);
        _passwordTF.font = LGFontWeight(16, UIFontWeightMedium);
        _passwordTF.leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, viewPix(16), viewPix(56))];
        _passwordTF.leftViewMode = UITextFieldViewModeAlways;
    }
    return _passwordTF;
}

-(UITextField *)smscodeTF{
    if(!_smscodeTF){
        _smscodeTF = [[UITextField alloc]initWithFrame:CGRectMake(viewPix(16), viewPix(84), Screen_W-viewPix(32), viewPix(56))];
        _smscodeTF.backgroundColor = [UIColor colorWithString:@"#F2F1F8"];
        _smscodeTF.tintColor = [UIColor colorWithString:@"#282828"];
        _smscodeTF.textColor = [UIColor colorWithString:@"#282828"];
        _smscodeTF.textAlignment = NSTextAlignmentLeft;
        _smscodeTF.keyboardType = UIKeyboardTypePhonePad;
        _smscodeTF.placeholder = @"请输入";
        _smscodeTF.cornerRidus = viewPix(28);
        _smscodeTF.font = LGFontWeight(16, UIFontWeightMedium);
        _smscodeTF.leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, viewPix(16), viewPix(56))];
        _smscodeTF.leftViewMode = UITextFieldViewModeAlways;
    }
    return _smscodeTF;
}

-(UIButton *)codeBtn{
    if(!_codeBtn){
        _codeBtn = [UIButton buttonWithTitle:@"获取验证码" titleFont:LGFont(14) normalColor:kThemeColor selectColor:@"#61616D"];
        _codeBtn.frame = CGRectMake(Screen_W-viewPix(32)-viewPix(100), 0, viewPix(100), viewPix(56));
        [_codeBtn addTarget:self action:@selector(getSmsCodeAction:) forControlEvents:UIControlEventTouchUpInside];
        UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, viewPix(18), 1, viewPix(20))];
        lineView.backgroundColor = [UIColor colorWithString:@"#D4D3D9"];
        [_codeBtn addSubview:lineView];
    }
    return _codeBtn;
}

-(UIButton *)nextBtn{
    if(!_nextBtn){
        _nextBtn = [UIButton buttonWithTitle:@"下一步" topMargin:Screen_H-topBarHeight-viewPix(88)];
        [_nextBtn addTarget:self action:@selector(nextBtnAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _nextBtn;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
